<template>
  <div>
    <!-- table -->
    <a-card>
      <a-button type="primary" @click="newMember1"> 新增 </a-button>
      <a-modal
        title="新增学生表信息"
        :visible="visible"
        :confirm-loading="confirmLoading"
        ok-text="新增"
        cancel-text="取消"
        @ok="saveRow(record)"
        @cancel="handleCancel"
        >
        <a-input  placeholder="Basic usage" />

        <a-select
          default-value="男"
          style="width: 120px"
          @change="handleChange"
        >
          <a-select-option value="man"> 男 </a-select-option>
          <a-select-option value="woman"> 女 </a-select-option>
        </a-select>
      </a-modal>

      <br />

      <a-table
        :pagination="pagination"
        :rowSelection="rowSelection"
        :columns="columns"
        :dataSource="data"
        @change="TableChange"
        rowKey="id"
      >
        <template
          v-for="(col, i) in ['name', 'StuId', 'Class', 'sex']"
          v-slot:[col]="{ text, record }"
        >
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="(e) => handleChange(e.target.value, record.key, col)"
          />
          
          <template v-else>{{ text }}</template>
        </template>

        <template #operation="{ record }">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="是否要删除此行？"
                @confirm="remove(record.key)"
              >
                <a>删除</a>
              </a-popconfirm>
            </span>

            <span v-else>
              <a @click="saveRow(record)">保存1</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.key)">取消1</a>
            </span>
          </template>

          <span v-else>
            <a @click="toggle(record.key)">操作中的编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除？" @confirm="remove(record.key)">
              <a>操作中的删除</a>
            </a-popconfirm>
          </span>

          <a-divider type="vertical" />
          <a @click="newMember">更多操作</a>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  Form,
  Card,
  Button,
  Input,
  DatePicker,
  Select,
  TimePicker,
  Popover,
  Table,
  Popconfirm,
  Divider,
  message,
} from "ant-design-vue";
import {
  ExclamationOutlined,
  CloseCircleOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import RepositoryForm from "./components/ResponsitoryForm.vue";
import TaskForm from "./components/TaskForm.vue";
import FooterToolBar from "./components/FooterToolbar.vue";
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

const fieldLabels = {
  name: "仓库名",
  url: "仓库域名",
  owner: "仓库管理员",
  approver: "审批人",
  dateRange: "生效日期",
  type: "仓库类型",
  name2: "任务名",
  url2: "任务描述",
  owner2: "执行人",
  approver2: "责任人",
  dateRange2: "生效日期",
  type2: "任务类型",
};

export default {
  name: "AdvancedForm",
  components: {
    FooterToolBar,
    RepositoryForm,
    TaskForm,
    ATable: Table,
    ADivider: Divider,
    AForm: Form,
    ACard: Card,
    AButton: Button,
    APopover: Popover,
    APopconfirm: Popconfirm,
    ARangePicker: RangePicker,
    ATimePicker: TimePicker,
    AInput: Input,
    AFormItem: FormItem,
    ASelect: Select,
    ASelectOption: Option,
    ExclamationOutlined,
    CloseCircleOutlined,
    PlusOutlined,
  },
  computed: {
    ...mapState({
      collapse: (state) => state.collapse,
    }),
  },
  data() {
    return {
      loading: false,
      memberLoading: false,
      // collapse: false,
      current: 2,
      visible: false,

      pagination: {
        defaultPageSize: 5,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true, //是否可以改变 pageSize
        pageSizeOptions: ["5", "10", "15", "20"],
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
      },
      // table
      columns: [
        {
          title: "成员姓名",
          dataIndex: "name",
          key: "name",
          width: "20%",
          slots: { customRender: "name" },
        },
        {
          title: "学号",
          dataIndex: "StuId",
          key: "StuId",
          width: "20%",
          slots: { customRender: "StuId" },
        },
        {
          title: "班级",
          dataIndex: "Class",
          key: "Class",
          width: "20%",
          slots: { customRender: "Class" },
        },
        {
          title: "性别",
          dataIndex: "sex",
          key: "sex",
          width: "20%",
          slots: { customRender: "sex" },
        },
        {
          title: "操作",
          key: "action",
          slots: { customRender: "operation" },
        },
      ],
      data: [
        {
          key: "1",
          name: "小陈",
          StuId: "18001",
          editable: false,
          Class: "1班",
          sex: "男",
        },
        {
          key: "2",
          name: "李莉",
          StuId: "18002",
          editable: false,
          Class: "1班",
          sex: "男",
        },
        {
          key: "3",
          name: "王小帅",
          StuId: "18003",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "4",
          name: "刘德华",
          StuId: "18004",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "5",
          name: "张学友",
          StuId: "18005",
          editable: false,
          Class: "2班",
          sex: "男",
        },
        {
          key: "6",
          name: "郭富城",
          StuId: "18006",
          editable: false,
          Class: "4班",
          sex: "男",
        },
        {
          key: "7",
          name: "黎明",
          StuId: "18007",
          editable: false,
          Class: "1班",
          sex: "男",
        },
        {
          key: "8",
          name: "王小帅",
          StuId: "18008",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "9",
          name: "王小帅",
          StuId: "18009",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "10",
          name: "王小帅",
          StuId: "18010",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "11",
          name: "王小帅",
          StuId: "18011",
          editable: false,
          Class: "3班",
          sex: "男",
        },
        {
          key: "12",
          name: "王小帅",
          StuId: "18012",
          editable: false,
          Class: "3班",
          sex: "男",
        },
      ],

      errors: [],
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
    },
    //左上角新增按钮
    newMember1() {
      this.visible = true;
      const length = this.data.length;
      this.data.push({
        key:
          length === 0
            ? "1"
            : (parseInt(this.data[length - 1].key) + 1).toString(),
        
        name: "",
        StuId: "",
        Class: "",
        sex: "",
        isNew: true,
      });
    },

    //更多操作新增
    newMember() {
      const length = this.data.length;
      this.data.push({
        key:
          length === 0
            ? "1"
            : (parseInt(this.data[length - 1].key) + 1).toString(),
        name: "",
        StuId: "",
        Class: "",
        sex: "",
        editable: true,
        isNew: true,
      });
    },

    //点击取消
    handleCancel(e) {
      //console.log("Clicked cancel button");
      this.visible = false;
    },

    remove(key) {
      const newData = this.data.filter((item) => item.key !== key);
      this.data = newData;
    },

    saveRow(record) {
      this.visible = false;
      this.memberLoading = true;
      const { key, name, StuId, Class, sex } = record;
      if (!name || !StuId || !Class || !sex) {
        this.memberLoading = false;
        this.$message.error("请填写完整成员信息。");
        return;
      }

      console.log(record)
      // 模拟网络请求、卡顿 800ms
      new Promise((resolve) => {
        setTimeout(() => {
          resolve({ loop: false });
        }, 800);
      }).then(() => {
        const target = this.data.find((item) => item.key === key);
        target.editable = false;
        target.isNew = false;
        this.memberLoading = false;
      });
    },
    toggle(key) {
      const target = this.data.find((item) => item.key === key);
      target._originalData = { ...target };
      target.editable = !target.editable;
    },
    getRowByKey(key, newData) {
      const data = this.data;
      return (newData || data).find((item) => item.key === key);
    },
    cancel(key) {
      const target = this.data.find((item) => item.key === key);
      Object.keys(target).forEach((key) => {
        target[key] = target._originalData[key];
      });
      target._originalData = undefined;
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },

    // 最终全页面提交
    validate() {
      let isCorrect = false;
      let isTaskCorrect = false;
      const {
        $refs: { repository, task },
        $notification,
      } = this;
      const repositoryForm = new Promise((resolve, reject) => {
        repository.form.validateFields((err, values) => {
          if (err) {
            reject(err);
            isCorrect = false;
            return;
          }
          isCorrect = true;
          resolve(values);
        });
      });
      const taskForm = new Promise((resolve, reject) => {
        task.form.validateFields((err, values) => {
          if (err) {
            reject(err);
            isTaskCorrect = false;
            return;
          }
          isTaskCorrect = true;
          resolve(values);
        });
      });
      if (isCorrect && isTaskCorrect) {
        console.log("接收到的表单数据:", {
          ...repository.form.getFieldsValue(),
          ...task.form.getFieldsValue(),
        });
        message.success("提交成功");
      }
      // clean this.errors
      this.errors = [];
      Promise.all([repositoryForm, taskForm])
        .then((values) => {
          $notification["error"]({
            message: "Received values of form:",
            description: JSON.stringify(values),
          });
        })
        .catch(() => {
          const errors = Object.assign(
            {},
            repository.form.getFieldsError(),
            task.form.getFieldsError()
          );
          const tmp = { ...errors };
          this.errorList(tmp);
        });
    },
    errorList(errors) {
      if (!errors || errors.length === 0) {
        return;
      }
      this.errors = Object.keys(errors)
        .filter((key) => errors[key])
        .map((key) => ({
          key: key,
          message: errors[key][0],
          fieldLabel: fieldLabels[key],
        }));
    },
    scrollToField(fieldKey) {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.card {
  margin-bottom: 24px;
}
.popover-wrapper {
  /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
    min-width: 256px;
    max-height: 290px;
    padding: 0;
    overflow: auto;
  }
}
.antd-pro-pages-forms-style-errorIcon {
  user-select: none;
  margin-right: 24px;
  color: #f5222d;
  cursor: pointer;
  i {
    margin-right: 4px;
  }
}
.antd-pro-pages-forms-style-errorListItem {
  padding: 8px 16px;
  list-style: none;
  border-bottom: 1px solid #e8e8e8;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #e6f7ff;
  }
  .antd-pro-pages-forms-style-errorIcon {
    float: left;
    margin-top: 4px;
    margin-right: 12px;
    padding-bottom: 22px;
    color: #f5222d;
  }
  .antd-pro-pages-forms-style-errorField {
    margin-top: 2px;
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
  }
}
#components-pagination-demo-mini {
  margin-bottom: 24px;
  float: right;
}
</style>

